package com.xli.sso.security.identity;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.xli.organ.user.frameuser.entity.FrameUser;
import com.xli.ui.module.framemodule.entity.FrameModule;
import com.xli.ui.module.framemodule.service.IFrameModuleService;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Data
public class LoginUser implements UserDetails {

    private final String loginId;
    private final Long userId;
    private final String username;
    private final String mobile;
    private final FrameUser frameUser;
    private String avatar;
    private String token;
    private Long loginTime;
    private Long expireTime;

    public LoginUser(String loginId, FrameUser frameUser) {
        this.loginId = loginId;
        this.userId = frameUser.getId();
        this.frameUser = frameUser;
        this.username = frameUser.getUsername();
        this.mobile = frameUser.getMobile();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        IFrameModuleService iFrameModuleService = SpringUtil.getBean(IFrameModuleService.class);
        List<FrameModule> frameModuleList = iFrameModuleService.findModuleListByUserId(frameUser.getId());
        Set<String> permissionNames = frameModuleList.stream()
                .map(FrameModule::getPermission)
                .filter(StrUtil::isNotBlank)
                .collect(Collectors.toSet());
        return AuthorityUtils.createAuthorityList(permissionNames);
    }

    @Override
    public String getPassword() {
        return frameUser.getPwd();
    }

    @Override
    public String getUsername() {
        return frameUser.getLogin_id();
    }
}
